<template>
  <div class="ky-container">
    <div @click="closeRight">
      <el-card shadow="hover" class="qf-box ky-card ky-card-hdbg" v-show="!isExtend">
        <el-form ref="form" :model="formData" :inline="true" class="ky-form-inline ky-form-inline-sm" label-width="80px">
          <el-form-item label="医院名称" prop="hospitalCode">
            <el-select size="small" class="param-type_input" v-model="formData.hospitalCode" @change="handleChange('hospital')" placeholder="请选择" filterable>
              <el-option v-for="(item,index) in mx_hospitalList" :key="index" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查部门">
            <el-select label="检查部门" size="small" @change="handleChange('dep')" class="param-type_input" v-model="formData.dep" placeholder="请选择" filterable clearable>
              <el-option v-for="(item,index) in depOptions" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="短信类型">
            <el-select label="短信类型" size="small" class="param-type_input" v-model="formData.type" placeholder="请选择" filterable clearable>
              <el-option v-for="(item,index) in messageTypeOptions" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="m-l-0 click-button" size="small" icon="el-icon-search" @click="search">查询</el-button>
            <el-button class="m-l-0 click-button" size="small" @click="resetParam" plain>重置</el-button>
            <el-button
              type="primary"
              size="small"
              @click.stop="getRightPanel(pageStatus.add)"><i class="el-icon-plus icon"></i> 新增短信模板</el-button>
            <el-button v-if="false" :type="isSortUp ? 'success':'warning'" size="small" @click.stop="sortData()"><i :class="isSortUp ? 'el-icon-sort-up':'el-icon-sort-down'"></i> {{isSortUp ? '正序' : '倒序'}}</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card shadow="hover" class="qf-box ky-card ky-card-hdbg content-height ky-mt10">
        <div class="content-title flex flex-row align-center">
          <span style="float: left;">短信列表&nbsp;&nbsp;</span>
          <span style="color: red;font-size: 14px;float: left;">【勾选任意一项支持批量启用,禁用,删除】</span>
        </div>
        <el-table
          ref="table"
          v-loading="loading"
          size="medium"
          :data="tableData"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange"
          class="ky-table"
          highlight-current-row>
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column align="left" fixed label="操作" width="240">
            <template slot-scope="scope">
              <div class="flex flex-row justify-center">
                <el-button
                  type="primary"
                  size="small"
                  @click.stop="getRightPanel(pageStatus.edit,scope.row)"><i class="el-icon-edit"></i> 编辑</el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click.stop="handleDelete(scope.$index, scope.row)"><i class="el-icon-delete"></i> 删除</el-button>
                <el-button :type="scope.row.isOpen == 'False' ? 'success':'warning'" size="small" @click.stop="handleLock(scope.row)"><i :class="scope.row.isOpen == 'False' ? 'el-icon-unlock':'el-icon-lock'"></i> {{scope.row.isOpen == 'False' ? '启用' : '禁用'}}</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="left" v-if="false" prop="id" label="Id" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="type" label="短信类型" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="dep" label="检查部门" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="dengjipart" label="检查部位" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="modality" label="检查设备" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="receivePerson" label="短信接收方" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="contentTemplate" label="短信内容模板" show-overflow-tooltip width="250"></el-table-column>
          <el-table-column align="left" prop="pattype" label="患者类型" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="age" label="开始年龄" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="ageEnd" label="结束年龄" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="checktype" label="扫描方式" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="delaytime" label="延迟分钟" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="receiveTel" label="接收电话" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="week" label="星期" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="appointmentType" label="预约来源" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="hisType" label="HIS类型" show-overflow-tooltip></el-table-column>
        </el-table>
        <paginationCont
          :total="totalCount"
          :page.sync="currentPage"
          :limit.sync="pageSize"
          @pagination="changePagination"
        />
      </el-card>
      <transition name="fade-form" mode="out-in">
        <div :class="{'toolBox-small':device !== 'mobile' && sidebar.opened,'toolBox-midul': device !== 'mobile' && !sidebar.opened,'toolBox-large':device == 'mobile','toolBox':true}" v-show="showToolBox">
          <div>
            <i class="el-icon-info icon blue-color"></i>
            <span class="toolBox-text">已选择<span class="blue-color">{{multipleSelection.length}}</span>项</span>
            <span class="cancle-click" @click="cancleChoose">取消选择</span>
          </div>
          <div>
            <!-- <el-button type="primary" size="small" @click="batchSetField('nurseStation')">批量设置护士站</el-button> -->
            <el-button type="warning" size="small" v-if="onFlag&&!offFlag" @click="batchSetStatus">批量禁用</el-button>
            <el-button type="success" size="small" v-else-if="!onFlag&&offFlag" @click="batchSetStatus">批量启用</el-button>
            <el-button type="danger" size="small" @click="batchDelete">批量删除</el-button>
          </div>
        </div>
      </transition>
    </div>
    <editMessage
      :hospital-code.sync="formData.hospitalCode"
      :form-data.sync="formData"
      :show-right.sync="showRight"
      :cur-status="curStatus"
      :row-data.sync="rowData"
      :title.sync="title"
      @refresh="search"
    ></editMessage>
  </div>
</template>
<script>
// import { getItemListFunc } from '@/api/common'
import editMessage from './editMessage'
import { PageStatus } from '@/utils/constant'
import paginationCont from '@/components/Pagination/index'
import {
  getDepList,
  getMessagePages,
  deleteMessage,
  setCloseMessage,
  setOpenMessage,
  getItemGroupList
} from '@/api/api.js'
export default {
  name: '',
  components: {
    paginationCont,
    editMessage
  },
  created() {
    this.$getHospitalList()
  },
  data() {
    return {
      isExtend: 0,
      pageStatus: PageStatus,
      formData: {
        hospitalCode: this.$store.state.user.hospitalCode,
        dep: '',
        type: ''
      },
      isSortUp: false,
      messageTypeOptions: [],
      multipleSelection: [],
      depOptions: [],
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      loading: false,
      tableData: [],
      showToolBox: false,
      onFlag: false,
      offFlag: false,
      showRight: false,
      bindShow: false,
      title: '',
      curStatus: '',
      rowData: {}
    }
  },
  mounted() {
    this.formData.hospitalCode = this.$store.state.user.hospitalCode || ''
    try {
      this.getDepOptions()
      this.getMessageType()
      this.search()
    } catch (err) {
      console.log(err)
    }
  },
  methods: {
    getDepOptions() {
      const params = {
        hospitalCode: this.formData.hospitalCode
      }
      return new Promise(resolve => {
        getDepList(params).then(res => {
          if (res.code === 10000) {
            this.depOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    // 短信类型
    async getMessageType() {
      let data = {
        HospitalCode: this.formData.hospitalCode,
        type: '短信类型'
      }
      getItemGroupList(data).then(res => {
        if (res && res.code == 10000) {
          this.messageTypeOptions = res.content.list
        }
      })
    },
    changePagination() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.fetchData()
        }
      })
    },
    cancleChoose() {
      // 取消选择
      this.multipleSelection = []
      this.$refs.table.clearSelection()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    search() {
      this.loading = true
      this.currentPage = 1
      this.fetchData()
    },
    fetchData() {
      this.cancleChoose()
      this.loading = true
      let data = {
        HospitalCode: this.formData.hospitalCode,
        Type: this.formData.type,
        Dep: this.formData.dep,
        sortOrder: this.formData.sortOrder,
        PageSize: this.pageSize, // 页面大小
        PageNumber: this.currentPage // 页码
      }
      getMessagePages(data).then(res => {
        this.loading = false
        if (res.code === 10000) {
          this.tableData = res.content.list
          this.totalCount = res.content.totalCount
          // console.error('this.tableData', this.tableData)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    batchDelete(i, row) {
      // 批量删除
      let confirmMsg = '此操作将永久批量删除该选中短信, 是否继续?'
      this.$confirm(confirmMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let successNum = 0
        let faliNum = 0
        for (let v of this.multipleSelection) {
          let data = {
            hospitalCode: this.formData.hospitalCode,
            id: v.id
          }
          await deleteMessage(data).then(res => {
            if (res && res.code === 10000) {
              successNum++
            } else {
              faliNum++
            }
          })
        }
        this.changePagination()
        this.$message.success(`已经成功删除` + successNum + '条,失败' + faliNum + '条')
        // 本地缓存排班管理的机房选择数据重置默认选项
        // this.$store.dispatch('user/getDefaultCheckRoomTree')
        // this.$store.dispatch('user/resetDefaultCheckRoom', [])
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleDelete(i, row) {
      let confirmMsg = '此操作将永久删除该短信, 是否继续?'
      if (this.rowData && this.rowData.id === row.id) {
        confirmMsg = '该条机房正在编辑, 是否删除?'
      }
      this.$confirm(confirmMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData(row)
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    deleteData(row) {
      let param = {
        hospitalCode: this.formData.hospitalCode,
        id: row.id
      }
      deleteMessage(param).then((res) => {
        if (res.code === 10000) {
          this.$message.success('删除成功')
          this.showRight = false
          this.bindShow = false
          this.changePagination()
          // 本地缓存排班管理的机房选择数据重置默认选项
          // this.$store.dispatch('user/getDefaultCheckRoomTree')
          // this.$store.dispatch('user/resetDefaultCheckRoom', [])
        }
      })
    },
    resetParam() {
      // 重置
      const resetForm = {
        hospitalCode: this.$store.state.user.hospitalCode,
        dep: '',
        type: ''
      }
      this.formData = Object.assign(this.formData, resetForm)
      this.getDepOptions()
    },
    // 获取右边form
    getRightPanel(status, params) {
      this.$refs.table.setCurrentRow(params)
      this.curStatus = status
      if (params) {
        this.rowData = params
        this.title = params.type
      } else {
        this.rowData = null
      }
      this.showRight = true
      this.bindShow = false
    },
    handleChange(val) {
      switch (val) {
        case 'hospital':
          this.depOptions = []
          this.formData.dep = ''
          this.formData.type = ''
          this.messageTypeOptions = []
          this.tableData = []
          this.totalCount = 0
          try {
            this.getDepOptions()
            this.getMessageType()
            this.search()
          } catch (err) {
            console.log(err)
          }
          this.$nextTick(() => {
            this.$refs.hospAreaDepFilter && this.$refs.hospAreaDepFilter.init()
          })
          break
        default:
          break
      }
    },
    handleLock(row) {
      let tip = row.isOpen == 'False' ? '启用' : '禁用'
      console.error('row.isOpen', row.isOpen)
      this.$confirm(`此操作将${tip}该短信, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.lockData(row)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    lockData(row) {
      let status = row.isOpen == 'False' ? '启用' : '禁用'
      let params = {
        id: row.id.toString(),
        hospitalCode: this.formData.hospitalCode
      }
      if (row.isOpen == 'True') {
        return new Promise(resolve => {
          setCloseMessage(params).then(res => {
            console.error('res', res)
            if (res && res.code === 10001) {
              this.$message.success('状态更新成功')
              this.changePagination()
              if (this.rowData && row.id === this.rowData.id) {
                this.$refs.editMessage.changeStatus(status)
              }
            }
          })
        })
      } else {
        setOpenMessage(params).then((res) => {
          if (res && res.code === 10000) {
            console.error('res', res)
            this.$message.success('状态更新成功')
            this.changePagination()
            if (this.rowData && row.id === this.rowData.id) {
              this.$refs.editMessage.changeStatus(status)
            }
          }
        })
      }
    },
    batchSetStatus() {
      // 批量禁用
      let tip = this.multipleSelection[0].isOpen == 'False' ? '启用' : '禁用'
      this.$confirm(`此操作将批量${tip}短信, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let successNum = 0
        let faliNum = 0
        for (let v of this.multipleSelection) {
          let data = {
            hospitalCode: this.formData.hospitalCode,
            id: v.id.toString()
          }
          if (v.isOpen == 'False') {
            await setOpenMessage(data).then(res => {
              // 改掉列表的数据
              if (res && res.code === 10000) {
                successNum++
              } else {
                faliNum++
              }
            })
          } else {
            await setCloseMessage(data).then(res => {
              // 改掉列表的数据
              if (res && res.code === 10000) {
                successNum++
              } else {
                faliNum++
              }
            })
          }
        }
        this.changePagination()
        this.$message.success(`已经成功${tip}` + successNum + '条,失败' + faliNum + '条')

        // 本地缓存排班管理的机房选择数据重置默认选项
        // this.$store.dispatch('user/getDefaultCheckRoomTree')
        // this.$store.dispatch('user/resetDefaultCheckRoom', [])
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    closeRight() {
      this.showRight = false
      this.bindShow = false
    },
    sortData() {
      this.loading = true
      this.formData.sortOrder = this.isSortUp ? 'ASC' : 'DESC'
      this.isSortUp = !this.isSortUp
      this.fetchData()
    }
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    device() {
      return this.$store.state.app.device
    }
  },
  watch: {
    multipleSelection(val) {
      if (val && val.length >= 1) {
        this.showToolBox = true
        this.onFlag = false
        this.offFlag = false
        val.forEach(el => {
          if (el.isOpen === 'True') {
            this.onFlag = true
          } else {
            this.offFlag = true
          }
        })
      } else {
        this.showToolBox = false
      }
    }
  }
}
</script>
<style lang='scss' scoped>
  .ky-container{
      .content-title{
          margin-bottom: 10px;
          span{
              font-size: 16px;
              font-family: PingFangSC-Medium, PingFang SC;
              font-weight: 600;
          }
          .add-button{
              width: 96px;
              height: 32px;
              margin-left: 16px;
          }
      }
      .toolBox{
          display: flex;
          justify-content: space-between;
          align-items: center;
          border-top: 1px solid #E5E7EC;
          padding: 12px 28px;
          position: fixed;
          bottom: 0;
          background: #fff;
          z-index: 10;
          margin-left: -20px;
          .toolBox-text{
              margin-left: 8px;
              font-size: 13px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              color: rgba(0, 0, 0, 0.65);
              span{
                  margin:0 4px;
              }
          }
          .cancle-click{
              cursor: pointer;
              font-size: 13px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              color: #919398;
              margin-left: 32px;
          }
    }
    .toolBox-small{
        width: calc(100% - 210px);
    }
    .toolBox-midul{
        width: calc(100% - 54px);
    }
    .toolBox-large{
        width: 100%
    }
  }
  .btn_right_setting{
      /* position: absolute; */
      /* right: 6px; */
      /* top: 2px; */
      /* right: 20px; */
      /* bottom: 2px; */
      margin-top: -5px;
      width: 65px;
      /* float: right; */
      float: left;
      /* z-index: 1000; */
  }
  .content-height >>> .el-card__body {
    min-height: 704px;
    /* max-height: 800px; */
  }
</style>
